import {Injectable} from '@angular/core';
import {App, Keyboard, ModalController, Platform} from "ionic-angular";
import {StorageProvider} from "@providers/storage";
import {env} from "@env/environment";
import {WechatJsSdkProvider} from "@providers/wechat-js-sdk";
import {DialogProvider} from "@providers/dialog";
import {InterfaceProvider} from "@providers/interface";
import {Util} from "@providers/util";

/*
  Generated class for the CommonProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class CommonProvider {

  backButtonPressed: boolean = false;  //用于判断返回键是否触发

  constructor(private platform: Platform,
              private storage: StorageProvider,
              private keyboard: Keyboard,
              private app: App,
              private modal: ModalController,
              private ifp: InterfaceProvider,
              private dialogService: DialogProvider,
              private wechat: WechatJsSdkProvider) {
  }

  initialization() {
    this.platform.ready().then(() => {
      this.wechat.initConfig();
    });
  }

  getRootPage(): string {
    if (env.indexPage) return env.indexPage;

    let rootPage = this.platform.getQueryParam("rootPage") ||
      env.rootPage || 'ManagerLoginPage';

    let userInfo = this.storage.read("userInfo");
    if (!userInfo) return rootPage;

    if (userInfo["PAGE"] != null && userInfo["PAGE"].length != 0) {
      let str = JSON.stringify(userInfo["PAGE"]);
      if (str.indexOf("SAZYT") != -1) {
        if (rootPage == 'WorkerLoginPage') {
          return "WorkerTabsPage";
        }
      } else if (str.indexOf("THY") != -1) {
        if (rootPage == 'ConsigneeLoginPage'||rootPage == 'WorkerLoginPage') {
          return "ConsigneeTabsPage";
        }
      }
    } else if (userInfo["PCRM_GW01"] == -1) {
      if (rootPage == 'ManagerLoginPage') {
        return "ManagerTabsPage";
      }
    } else if (!userInfo["PAGE"] && !userInfo["GW"] && rootPage == 'CustomerLoginPage'&&!Util.isNull(userInfo)) {
      return "CustomerTabsPage";
    }

    return rootPage;
  }

  registerBackButtonAction() {
    let showExit = () => {
      if (this.backButtonPressed) { //当触发标志为true时，即2秒内双击返回按键则退出APP
        this.platform.exitApp();
      } else {
        this.dialogService.showToast("再按一次退出应用", 2000)
        this.backButtonPressed = true;
        //2秒内没有再次点击返回则将触发标志标记为false
        setTimeout(() => this.backButtonPressed = false, 2000);
      }
    };
    this.platform.registerBackButtonAction(() => {
      debugger;
      if (this.keyboard.isOpen()) {
        this.keyboard.close();
        return;
      }
      //如果想点击返回按钮隐藏toast或loading或Overlay就把下面加上
      // this.ionicApp._toastPortal.getActive() || this.ionicApp._loadingPortal.getActive() || this.ionicApp._overlayPortal.getActive()
      let ionicApp = this.app._appRoot;
      let activePortal = ionicApp._modalPortal.getActive() || ionicApp._toastPortal.getActive() ||
        ionicApp._loadingPortal.getActive() || ionicApp._overlayPortal.getActive();
      if (activePortal) {
        activePortal.dismiss().catch(() => {
        });
        activePortal.onDidDismiss(() => {
        });
        return;
      }
      let viewList = this.app.getActiveNav().getViews();
      let canExit = viewList.length <= 1;
      return canExit ? showExit() : this.app.navPop();
    })
  }

  startChat(party_id_list) {
    this.ifp.post({
      interfaceId: "app.chat.createChatRoom",
      data: {persons: party_id_list}
    }).toPromise()
      .then(v => {
        let _modal = this.modal.create("ChatPage", {ROOM_ID: v['room_id'],ROOM_NAME:v['room_name']});
        _modal.present();
      })
      .catch(e => {
        this.dialogService.showAlert(e)
      })
  }
}
